package com.example.demo.filter;

import com.example.demo.config.LocalRateLimitConfig;
import com.example.demo.service.ILocalRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局限流拦截器
 *
 * @author zxb
 **/
@Component
@Slf4j
public class LocalRateLimitGlobalFilter implements Ordered, GlobalFilter {

    @Autowired
    private LocalRateLimitConfig.LocalRateLimitProperties localRateLimitProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ILocalRateLimiter localRateLimiter = localRateLimitProperties.getLocalRateLimiter();
        // 如果允许通行，没有超过该 key 的流量限制
        if (localRateLimiter.access(exchange.getRequest()).isAllowed()) {
            return chain.filter(exchange);
        } else {
            log.warn("limit key: {}, 已被限流", localRateLimiter.getLimitKey(exchange.getRequest()));
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        // 值越大优先级越低
        return 1;
    }
}
